<template>
  <div class="ai-assistant-container">
    <h3 class="section-title">AI助手</h3>
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.sender">
        <div class="content" v-html="formatMessage(msg.text)"></div>
      </div>
      <div v-if="isLoading" class="message bot">
        <div class="content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
      <div v-if="errorMsg" class="message bot error">
        <div class="content">{{ errorMsg }}</div>
      </div>
    </div>
    <div class="input-container">
      <el-input
          v-model="inputMessage"
          placeholder="输入您的问题..."
          @keyup.enter="sendMessage"
          :disabled="isLoading"
      >
        <template #append>
          <el-button
              icon="Promotion"
              @click="sendMessage"
              :loading="isLoading"
          >发送</el-button>
        </template>
      </el-input>
    </div>
    <div class="quick-actions">
      <el-button type="primary" plain @click="quickAction('buy')">购买电影票</el-button>
      <el-button type="success" plain @click="quickAction('orders')">查询订单</el-button>
      <el-button type="info" plain @click="quickAction('recommend')">电影推荐</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import aiService from '@/services/ai'

const inputMessage = ref('')
const messages = ref([
  {
    sender: 'bot',
    text: '您好，我是2023444062数据库大作业的电影购票小助手\n' +
        '我有如下功能：\n' +
        '1. 购买电影票（请提供电影名称）\n' +
        '2. 查询所有订单\n' +
        '3. 推荐热门电影\n' +
        '您也可以和我聊聊电影相关的话题~'
  }
])
const messagesContainer = ref(null)
const isLoading = ref(false)
const errorMsg = ref('')

// 格式化消息内容（将换行符转换为<br>标签）
const formatMessage = (text) => {
  return text.replace(/\n/g, '<br>')
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return
  errorMsg.value = ''

  // 添加用户消息
  messages.value.push({
    sender: 'user',
    text: inputMessage.value
  })

  // 添加空的bot消息作为占位
  const botMessage = {
    sender: 'bot',
    text: ''
  }
  messages.value.push(botMessage)

  isLoading.value = true
  const userMessage = inputMessage.value
  inputMessage.value = ''

  scrollToBottom()

  try {
    await aiService.sendMessageStream(
        userMessage,
        (chunk) => {
          botMessage.text += chunk
          scrollToBottom()
        }
    )
  } catch (error) {
    console.error('AI回复失败:', error)
    errorMsg.value = '抱歉，AI回复出现错误，请稍后再试。'
    botMessage.text = '抱歉，我暂时无法回答您的问题，请稍后再试。'
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 快速操作
const quickAction = (action) => {
  switch(action) {
    case 'buy':
      inputMessage.value = '我想购买电影票'
      break
    case 'orders':
      inputMessage.value = '查询我的订单'
      break
    case 'recommend':
      inputMessage.value = '推荐一些热门电影'
      break
  }
  sendMessage()
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.ai-assistant-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
  font-size: 18px;
  margin-bottom: 15px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  min-height: 250px;
  max-height: 350px;
  background-color: #fafafa;
}

.message {
  margin-bottom: 15px;
  display: flex;
}

.message.bot {
  justify-content: flex-start;
}

.message.user {
  justify-content: flex-end;
}

.message .content {
  max-width: 85%;
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.5;
  word-break: break-word;
}

.message.bot .content {
  background-color: #f0f2f5;
}

.message.user .content {
  background-color: #e54847;
  color: white;
}

.input-container {
  margin-top: auto;
}

.quick-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.quick-actions .el-button {
  flex: 1;
  margin: 0 5px;
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  margin: 0 2px;
  background-color: #909399;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.3s linear infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.15s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.3s;
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}

/* 错误提示样式 */
.message.error .content {
  background-color: #f8d7da;
  color: #721c24;
  padding: 10px;
  border-radius: 4px;
}
</style>